#include<iostream>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>

#define NUM 2
#define SIZE 1024

using namespace std;

void Write(pid_t wfd)
{
    char buff[SIZE];
    pid_t id = getpid();

    int count = 0;
    while(count <= 5)
    {
        buff[0] = 0;
        snprintf(buff, SIZE, "我的pid是%d,当前我的count是%d。", id, count);
        write(wfd, buff, strlen(buff));

        count++;
        sleep(1);
    }
}

void Read(pid_t rfd)
{
    char buff[SIZE];
    int n = 0;
    while((n = read(rfd, buff, SIZE)) != 0)
    {
        if(n == -1)
        {
            fprintf(stderr, "读取管道中的内容失败。\n");
            exit(-3);
        }
        buff[n] = 0;
        cout << "子进程说：" << buff << endl;
    }
}

int main()
{
    int pipefd[NUM];
    int n = pipe(pipefd);
    if(n == -1)
    {
        fprintf(stderr, "管道创建失败。\n");
        return -2;
    }

    pid_t pid  = fork();

    //子进程，写
    if(pid == 0)
    {
        close(pipefd[0]);
        Write(pipefd[1]);
        close(pipefd[1]);
        exit(0);
    }

    //父进程，读
    close(pipefd[1]);
    Read(pipefd[0]);
    close(pipefd[0]);
    pid_t rid = waitpid(pid, NULL, 0);
    if(rid < 0) return 3;

    return 0;
}